import _ from 'lodash'
import NoDataAvailable from '@/components/NoDataAvailable'
import { Dialog } from 'vant'
import shortid from 'shortid'

export default {
  components: {
    NoDataAvailable,
  },

  props: {
    // 列
    columns: {
      type: Array,
      default: () => [],
    },
    // add button show
    addButton: {
      type: Boolean,
      default: () => false,
    },
    // delete button
    deleteButton: {
      type: Boolean,
      default: () => false,
    },
    // 最大行数 0 === 不限
    maxRow: {
      type: Number,
      default: () => 0,
    },
    // 最大行数 0 === 不限
    minRow: {
      type: Number,
      default: () => 0,
    },
  },

  data () {
    return {
      // 表单组件
      formComponent: [],

      // 动态更新
      tabColumn: [],
    }
  },

  computed: {
    tableColumn: {
      get () {
        return this.tabColumn
      },
      set (val) {
        this.tabColumn = val
      },
    },

    formGenerator () {
      const temp = this.$_
        .map(this.$refs.tableColumn, (o) => o.$refs.formGenerator)
      return temp
    },

    collectInfo () {
      const temp = this.$_
        .map(this.formGenerator, ({ collectInfo = {} }, index) => this.$_
          .map(collectInfo, (o) => ({
            ...o,
            order: (index + 1),
          })))
      return temp
    },

    isFormComponent () {
      return this.formComponent.length > 0
    },

    isMaxRow () {
      if (this.maxRow <= 0) return false
      if (this.formComponent.length >= this.maxRow) {
        return true
      }
    },

    isMinRow () {
      if (this.minRow <= 0) return false
      if (this.formComponent.length <= this.minRow) {
        return true
      }
    },
  },

  watch: {
    value: {
      immediate: true,
      handler (val) {
        switch (val.length) {
          case 0: // 无人填写
            this.formComponent.push({
              row: this.columns,
              id: shortid.generate(),
            })
            break

          default: // 多个数据
            this.$_
              .forEach(val, ({ column }, index) => {
                this.formComponent.push({ row: [], id: shortid.generate() })
                this.$_
                  .forEach(column, ({ value: fv = [], field }) => {
                    const form = this.formComponent[index]

                    const isFvType = Array.isArray(fv)
                    form.row.push({
                      ...field,
                      field_value: isFvType ? fv : [fv],
                    })
                  })
              })
            break
        }
      },
    },
  },

  mounted () {
    this.$nextTick(() => {
      this.updatedRef()
    })
  },

  methods: {
    // 获取元素
    getElements () {
      const { tableColumn } = this.$refs
      let elements = []
      _.forEach(tableColumn, (o) => {
        elements.push(o.getElements())
      })
      elements = _.flattenDeep(elements)
      console.log(tableColumn, elements, 'tableColumnv')
      return elements
    },

    // updatedRef
    updatedRef () {
      this.tableColumn = this.$refs.tableColumn
    },

    // 创建行
    createRow ({ columns }) {
      this.formComponent.push({
        row: columns,
        id: shortid.generate(),
      })
    },

    // 新增行
    addRow () {
      if (this.isMaxRow) {
        this.$toast.fail(`最大行数${this.maxRow}！`)
        return this.isMaxRow
      }

      this.createRow({ columns: this.columns })
      this.updatedRef()
    },

    // 删除行
    deleteRow ({ id }) {
      if (!id) return
      if (this.isMinRow) {
        this.$toast.fail(`最小行数${this.minRow}！`)
        return this.minRow
      }

      Dialog.confirm({
        title: '删除',
        message: '请确认删除当前表格？',
      })
        .then(() => {
          this.formComponent = this.$_
            .filter(this.formComponent, (o) => id !== o.id)
          this.$toast.success('删除成功')
          this.updatedRef()
        })
        .catch(() => {
          // on cancel
        })
    },

    // 表单验证
    validate () {
      console.log(this.tableColumn, 'f--r')
      // console.log(this.formGenerator, 'f--r')
      const validateArr = []
      this.$_
        .forEach(this.formGenerator, ({ getElementAttribute }) => {
          validateArr.push(
            ...getElementAttribute('validate'),
          )
        })
      return validateArr
    },
  },
}
